package top.dreamcenter.rss.rsssolverweb.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.Configuration;
import top.dreamcenter.rss.rsssolverprotocal.RegisterSpider;
import top.dreamcenter.rss.rsssolverweb.util.PluginLoader;

import java.util.Set;

/**
 * 将插件注册到容器中
 */
@Configuration
public class PluginBeanRegistrar implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry( BeanDefinitionRegistry registry) throws BeansException {
        try {
            PluginLoader pluginLoader = new PluginLoader();
            Set<Class<?>> plugins = pluginLoader.loadPlugins();
            for (Class<?> pluginClass : plugins) {
                // 仅加了RegisterSpider注解的插件需要注册
                if (pluginClass.isAnnotationPresent(RegisterSpider.class)) {
                    BeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(pluginClass).getBeanDefinition();
                    registry.registerBeanDefinition(pluginClass.getSimpleName(), beanDefinition);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        // No-op
    }
}